package com.shj.em.base.handler;

import com.alibaba.fastjson.JSONException;
import com.shj.em.base.exception.BizException;
import com.shj.em.base.support.ResMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author Shen Huang Jian
 * @date 2018/11/4
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResMsg handleIllegalParamException(MethodArgumentNotValidException e) { // 处理方法参数的异常类型
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String tips = "参数不合法: ";
        if (errors.size() > 0) {
            tips += errors.get(0).getDefaultMessage() + ", ";
        }

        return ResMsg.error(tips);
    }

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public ResMsg handleBizException(BizException be){
        log.error(be.getMessage(), be);
        return ResMsg.error(be.getMessage());
    }

    @ExceptionHandler(JSONException.class)
    @ResponseBody
    public ResMsg handleJSONException(JSONException be){
        log.error(be.getMessage(), be);
        return ResMsg.error("MIN99003-字符串必须是JSON格式。");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResMsg exceptionHandle(Exception e) {
        log.error(e.getMessage(), e);
        // 前端调用后端一个不存在的 Restful 接口时，会抛下面的错误信息
        if("java.util.LinkedHashMap cannot be cast to com.kedacom.ctsp.web.controller.message.ResMsg".equals(e.getMessage())){
            return ResMsg.error("MIN99002-访问的接口不存在。");
        }
        return ResMsg.error("MIN99001-服务器内部错误");
    }
}
